package com.rjwh.dingdong.client.receiver;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.NotificationCompat;

import com.aishua.lib.utils.AsStrUtils;
import com.alibaba.fastjson.JSON;
import com.igexin.sdk.PushConsts;
import com.igexin.sdk.PushManager;
import com.rjwh.dingdong.client.R;
import com.rjwh.dingdong.client.activity.webbrowser.OaGameActivity;
import com.rjwh.dingdong.client.application.AppManager;
import com.rjwh.dingdong.client.application.MyApplication;
import com.rjwh.dingdong.client.bean.localbean.PushMsgData;
import com.rjwh.dingdong.client.constant.LocalConstant;
import com.rjwh.dingdong.client.network.ApiRequest;
import com.rjwh.dingdong.client.util.AppUtil;
import com.rjwh.dingdong.client.util.LogUtil;
import com.rjwh.dingdong.client.util.UrlUtil;

/**
 * 项目名称：whrjwh-parent
 * 类描述：
 * 创建人：wby
 * 创建时间：2016/10/11 9:03
 * 修改人：wby
 * 修改时间：2016/10/11 9:03
 * 修改备注：
 *
 * @version V1.0
 */
public class GeTuiPushReceiver extends BroadcastReceiver {


    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        LogUtil.d("GeTuiPushReceiver", "onReceive() action=" + bundle.getInt("action"));

        switch (bundle.getInt(PushConsts.CMD_ACTION)) {
            case PushConsts.GET_MSG_DATA:
                // 获取透传数据
                // String appid = bundle.getString("appid");
                byte[] payload = bundle.getByteArray("payload");

                String taskid = bundle.getString("taskid");
                String messageid = bundle.getString("messageid");

                // smartPush第三方回执调用接口，actionid范围为90000-90999，可根据业务场景执行
                boolean result = PushManager.getInstance().sendFeedbackMessage(context, taskid, messageid, 90001);
                LogUtil.d("GeTuiPushReceiver", "第三方回执接口调用" + (result ? "成功" : "失败"));

                if (payload != null) {
                    String data = new String(payload);
                    LogUtil.d("GeTuiPushReceiver", "receiver payload : " + data);
                    doAction(context, data);
                }
                break;

            case PushConsts.GET_CLIENTID:
                // 获取ClientID(CID)
                // 第三方应用需要将CID上传到第三方服务器，并且将当前用户帐号和CID进行关联，以便日后通过用户帐号查找CID进行消息推送
                String cid = bundle.getString("clientid");
                LogUtil.d("GeTuiPushReceiver", "cid = " + cid);
                MyApplication.spUtil.setStrPreference(MyApplication.getInstance(), LocalConstant.SP_CLIENTID, cid);
//                if (MyApplication.spUtil.getBoolPreferenceByParamName(MyApplication.getInstance(), LocalConstant.SP_IS_LOGINED)) {
                //登录状态下调用接口
                try {
                    ApplicationInfo appInfo = context.getPackageManager()
                            .getApplicationInfo(context.getPackageName(),
                                    PackageManager.GET_META_DATA);
                    String msg = appInfo.metaData.getString("PUSH_APPID");
                    LogUtil.e("GeTuiPushReceiver", "PUSH_APPID:" + msg);
                    if (!AsStrUtils.isEmpty(msg)) {
                        LogUtil.d("GeTuiPushReceiver", "绑定推送");
                        ApiRequest.pushBindingForAppId(msg, cid, null);
                    }
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }
//                ApiRequest.pushBinding(cid, null);
//                LogUtil.d("GeTuiPushReceiver", "pushBinding");
//                }
                break;
            case PushConsts.GET_SDKONLINESTATE:
                boolean online = bundle.getBoolean("onlineState");
                LogUtil.d("GeTuiPushReceiver", "online = " + online);
                break;

            case PushConsts.SET_TAG_RESULT:
                String sn = bundle.getString("sn");
                String code = bundle.getString("code");

                String text = "设置标签失败, 未知异常";
                switch (Integer.valueOf(code)) {
                    case PushConsts.SETTAG_SUCCESS:
                        text = "设置标签成功";
                        break;

                    case PushConsts.SETTAG_ERROR_COUNT:
                        text = "设置标签失败, tag数量过大, 最大不能超过200个";
                        break;

                    case PushConsts.SETTAG_ERROR_FREQUENCY:
                        text = "设置标签失败, 频率过快, 两次间隔应大于1s";
                        break;

                    case PushConsts.SETTAG_ERROR_REPEAT:
                        text = "设置标签失败, 标签重复";
                        break;

                    case PushConsts.SETTAG_ERROR_UNBIND:
                        text = "设置标签失败, 服务未初始化成功";
                        break;

                    case PushConsts.SETTAG_ERROR_EXCEPTION:
                        text = "设置标签失败, 未知异常";
                        break;

                    case PushConsts.SETTAG_ERROR_NULL:
                        text = "设置标签失败, tag 为空";
                        break;

                    case PushConsts.SETTAG_NOTONLINE:
                        text = "还未登陆成功";
                        break;

                    case PushConsts.SETTAG_IN_BLACKLIST:
                        text = "该应用已经在黑名单中,请联系售后支持!";
                        break;

                    case PushConsts.SETTAG_NUM_EXCEED:
                        text = "已存 tag 超过限制";
                        break;

                    default:
                        break;
                }

                LogUtil.d("GeTuiPushReceiver", "settag result sn = " + sn + ", code = " + code);
                LogUtil.d("GeTuiPushReceiver", "settag result sn = " + text);
                break;
            case PushConsts.THIRDPART_FEEDBACK:
                /*
                 * String appid = bundle.getString("appid"); String taskid =
                 * bundle.getString("taskid"); String actionid = bundle.getString("actionid");
                 * String result = bundle.getString("result"); long timestamp =
                 * bundle.getLong("timestamp");
                 *
                 * Log.d("GetuiSdkDemo", "appid = " + appid); Log.d("GetuiSdkDemo", "taskid = " +
                 * taskid); Log.d("GetuiSdkDemo", "actionid = " + actionid); Log.d("GetuiSdkDemo",
                 * "result = " + result); Log.d("GetuiSdkDemo", "timestamp = " + timestamp);
                 */
                break;

            default:
                break;
        }
    }

    private void doAction(Context context, String data) {
        try {
            PushMsgData pushMsgData = JSON.parseObject(data, PushMsgData.class);
            if (pushMsgData != null) {
                String actionid = pushMsgData.getActionid();
                String actionurl = pushMsgData.getActionurl();
                String content = pushMsgData.getContent();
                String title = pushMsgData.getTitle();

                if (AsStrUtils.isEmpty(actionid) || AsStrUtils.isEmpty(actionurl) || AsStrUtils.isEmpty(content) || AsStrUtils.isEmpty(title)) {
                    return;
                }

                //当前APP处于前台
                if (AppUtil.isBackground(context)) {
                    LogUtil.e("GeTuiPushReceiver", "isBackground = true");
                    if (AppUtil.isForeground(context, OaGameActivity.class.getName())) {
                        LogUtil.e("GeTuiPushReceiver", "isBackground   &&   OaGameActivity  isForeground ");
                        sendNotify(context, title, content, actionurl, actionid);
                    } else {
                        showDialog(context, title, content, actionurl, actionid);
                    }
                } else {
                    LogUtil.e("GeTuiPushReceiver", "isBackground = false");
                    sendNotify(context, title, content, actionurl, actionid);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void sendNotify(final Context context, String title, String content, final String actionurl, final String actionid) {

        //设置点击通知栏的动作为启动另外一个广播
        Intent broadcastIntent = new Intent(context, NotificationReceiver.class);
        broadcastIntent.putExtra("actionurl", actionurl);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
        builder.setAutoCancel(true)
                .setContentTitle(title)
                .setContentText(content)
                .setTicker(title + content)
                .setContentIntent(pendingIntent)
                .setDefaults(Notification.DEFAULT_ALL)
                .setSmallIcon(R.drawable.icon_logo);

        LogUtil.d("GeTuiPushReceiver", "showNotification");
        NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        manager.notify(Integer.parseInt(actionid), builder.build());
    }


    private void showDialog(final Context context, String title, String content, final String actionurl, final String actionid) {
        final Activity activity = AppManager.getAppManager().currentActivity();
        if (activity != null && !activity.isFinishing()) {
            LogUtil.e("GeTuiPushReceiver", "activity: " + activity.getClass());

            AlertDialog dialog = new AlertDialog.Builder(activity)
                    .setTitle(title)
                    .setMessage(content)
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            UrlUtil.handelUrl(activity, actionurl, true);
                        }
                    })
                    .show();
        } else {
            sendNotify(context, title, content, actionurl, actionid);
        }

    }
}
